package com.unicloud.medical.oss.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CommonUtil {
    public static String formatObjectName(String objectName) {
        String newObjectName = StringUtils.trimToNull(objectName);
        if (Objects.isNull(newObjectName)) return null;

        if (newObjectName.startsWith("/")) {
            return newObjectName.substring(1);
        }
        return newObjectName;
    }

    public static String formatFolder(String folder) {
        String newFolder = formatObjectName(folder);
        if (Objects.isNull(newFolder)) return null;

        if (newFolder.endsWith("/")) {
            return newFolder.substring(0, newFolder.length() - 1);
        }

        return newFolder;
    }

    /**
     * 添加到压缩文件
     * @param name
     * @param inputStream
     * @param zipOutputStream
     * @throws Exception
     */
    public static void zip(String name, InputStream inputStream, ZipOutputStream zipOutputStream) throws Exception {
        if (Objects.isNull(inputStream) || Objects.isNull(zipOutputStream) || StringUtils.isEmpty(name)) return;

        zipOutputStream.putNextEntry(new ZipEntry(name));

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) >= 0) {
            zipOutputStream.write(buffer, 0, length);
        }

        zipOutputStream.closeEntry();
    }

    public static String buildName(String ossName, String ossType, String endpoint) {
        if (StringUtils.isNotEmpty(ossName)) return ossName;
        StringBuilder builder = new StringBuilder();
        builder.append(ossType);

        if (StringUtils.isEmpty(endpoint)) return builder.toString();

        String[] split = endpoint.split("//");
        if (split == null || split.length == 0 || split.length > 2) return builder.toString();
        if (split.length == 1) {
            return builder.append(":").append(endpoint).toString();
        }

        return builder.append(":").append(split[1]).toString();
    }

}
